<?php

namespace app\api\controller;

use app\data\model\DataEnterpriseFreePolicy;
use app\data\model\DataMsjx;
use app\data\model\DataPolicyItem;
use app\data\model\DataQiyeBiaoqian;
use app\data\model\DataQiyeRzinfo;
use app\data\model\DataQiyeXinxiku;
use think\admin\Controller;
use think\facade\Db;

class Msjx extends Controller
{

    //免申即享
    public function getMsjxAllList()
    {
        $page  = input('page', 1);
        $limit = input('limit', 10);
        $key   = input('key');

        $where['deleted'] = 0;


        if (!empty($key)) {
            $where[] = ['title', 'like', '%' . $key . '%'];
        }

        $list = Db::name('data_msjx')->where($where)->order('create_at desc')->paginate($limit, false, ['page' => $page]);

        // 引用方式遍历集合并修改数据
        $list->each(function (&$item)
        {
            if (!empty($item['admin_id'])) {
                $item['admin_name'] = Db::name("system_user")->where('id', $item['admin_id'])->value('nickname');
            } else {
                $item['admin_name'] = '';
            }

            if (!empty($item['sbjzrq'])) {
                if ($item['sbjzrq'] > time()) {

                    // 计算剩余秒数
                    $remainingSeconds = $item['sbjzrq'] - time();

                    if ($remainingSeconds >= 86400) { // 大于等于 1 天
                        // 计算剩余天数
                        $remainingDays = floor($remainingSeconds / 86400);
                        $item['syts']  = "{$remainingDays}天";
                    } else {
                        // 小于 1 天，计算剩余小时数
                        $remainingHours = floor($remainingSeconds / 3600);
                        $item['syts']   = "{$remainingHours}小时";
                    }
                } else {
                    $item['syts'] = '已结束';
                }

            } else {
                $item['syts'] = '';
            }


            if (!empty($item['ctrq'])) {

                $item['ctrq_txt'] = date('Y-m-d', $item['ctrq']);

            } else {
                $item['ctrq_txt'] = '';
            }

            if (!empty($item['sbjzrq'])) {

                $item['sbjzrq_txt'] = date('Y-m-d', $item['sbjzrq']);

            } else {
                $item['sbjzrq_txt'] = '';
            }


            switch ($item['tj_status']) {
                case 1:
                    $item['tj_status_txt'] = '已提交';
                    break;
                case 2:
                    $item['tj_status_txt'] = '审核中';
                    break;
                case 3:
                    $item['tj_status_txt'] = '已公示';
                    break;
                case 4:
                    $item['tj_status_txt'] = '已落实';
                    break;
                default:
                    $item['tj_status_txt'] = '未知';
                    break;
            }


            return $item;
        });

        // 获取分页数据
        $data = [
            'list'      => $list->items(),
            'total'     => $list->total(),
            'last_page' => $list->lastPage(),
        ];

        // 输出分页数据
        return_msg(200, '查询成功', $data);
    }

    public function getFreePolicyList()
    {
        $page   = input('page', 1);
        $limit  = input('limit') ?? 50;
        $key    = input('key');
        $userId = input('user_id');

        $where['deleted'] = 0;
        if (!empty($key)) {
            $where[] = ['title', 'like', '%' . $key . '%'];
        }
        // $list = DataMsjx::where($where)->order('create_at desc')->paginate(['list_rows' => $limit, 'page' => $page])->toArray();
        if (!$userId) {
//            return_error('请先登录');
        }
        //查询用户关联的企业
//        $user = DataQiyeRzinfo::query()->where('user_id', $userId)->where('deleted', 0)->find();
//        if (!$user) {
//            return_error('当前用户没有企业认证，请先认证企业');
//        }
//        $enterpriseId = $user->qrxxk_id;
        //根据企业id查询关联的政策
//        $policyIds = DataEnterpriseFreePolicy::query()->where('enterprise_id', $enterpriseId)->column('policy_id');
//        $list      = DataMsjx::where($where)->whereIn('id', $policyIds)->order('create_at desc')->paginate(['list_rows' => $limit, 'page' => $page])->toArray();

        $list   = DataMsjx::where($where)->order('ctrq desc')->paginate(['list_rows' => $limit, 'page' => $page])->toArray();

        foreach ($list['data'] as &$item) {
            $item['ctrq'] = date('Y-m-d H:i:s', $item['ctrq']);
        }
        unset($item);
        $data = [
            'list'      => $list['data'] ?? [],
            'total'     => $list['total'] ?? 0,
            'last_page' => $list['last_page'] ?? 0,
        ];
        return_msg(200, 'success', $data);
    }

    //查看免申即享详情
    public function getMsjxInfo()
    {

        $id      = input('id');
//        $user_id = input('user_id');

        if (empty($id)) {
            return_error('缺少id');
        }

        $info = Db::name("data_msjx")->where('id', $id)->find();

        if (empty($info)) {
            return_error('未找到文章记录');
        }


//        if (!empty($info['qybq'])) {
//
//            $qybq_array       = explode(',', $info['qybq']);
//            $info['qybq_txt'] = '';
//            $i                = 0;
//            foreach ($qybq_array as $qybq) {
//                if ($i > 0) {
//                    $info['qybq_txt'] .= ',';
//                }
//                $info['qybq_txt'] .= Db::name("data_qiye_biaoqian")->where('id', $qybq)->value('name');
//                $i++;
//            }
//        } else {
//            $info['qybq_txt'] = '';
//        }


        //        if(!empty($info['admin_id'])){
        //            $info['admin_name'] = Db::name("system_user")->where('id',$info['admin_id'])->value('nickname');
        //        }else{
        //            $info['admin_name'] = '';
        //        }

        if (!empty($info['ctrq'])) {

            $info['ctrq_txt'] = date('Y-m-d', $info['ctrq']);

        } else {
            $info['ctrq_txt'] = '';
        }


        if (!empty($info['sbjzrq'])) {

            $info['sbjzrq_txt'] = date('Y-m-d', $info['sbjzrq']);

        } else {
            $info['sbjzrq_txt'] = '';
        }


        if (empty($user_id)) {
            $info['is_tijiao'] = 0;
            $info['is_pj']     = 0;
            $info['pf']        = '';
            $info['pjnr']      = '';


        } else {
            //            $info['is_tijiao'] = Db::name("data_msjx_user")->where('user_id',$user_id)->where('msjx_id',$info['id'])->where('deleted',0)->count();

            $qiye = Db::name("data_qiye_rzinfo")->where('user_id', $user_id)->where('deleted', 0)->find();
            if (!empty($qiye)) {


                $msjx_user = Db::name("data_msjx_user")->where('msjx_id', $info['id'])->where('qrxxk_id', $qiye['qrxxk_id'])->where('deleted', 0)->find();

                if (empty($msjx_user)) {
                    $info['is_tijiao'] = 0;

                    $info['is_pj'] = 0;
                    $info['pf']    = '';
                    $info['pjnr']  = '';
                } else {
                    $info['is_tijiao'] = 1;
                    if (empty($msjx_user['pf'])) {
                        $info['is_pj'] = 0;
                    } else {
                        $info['is_pj'] = 1;
                    }
                    $info['pf']   = $msjx_user['pf'];
                    $info['pjnr'] = $msjx_user['pjnr'];

                }

            } else {

                $info['is_tijiao'] = 0;

                $info['is_pj'] = 0;
                $info['pf']    = '';
                $info['pjnr']  = '';

            }


        }


        switch ($info['tj_status']) {
            case 1:
                $info['tj_status_txt'] = '已提交';
                break;
            case 2:
                $info['tj_status_txt'] = '审核中';
                break;
            case 3:
                $info['tj_status_txt'] = '已公示';
                break;
            case 4:
                $info['tj_status_txt'] = '已落实';
                break;
            default:
                $info['tj_status_txt'] = '未知';
                break;
        }


        switch ($info['zhuangtai']) {
            case 1:
                $info['zhuangtai_txt'] = '进行中';
                break;
            case 2:
                $info['zhuangtai_txt'] = '已完成';
                break;
            default:
                $info['zhuangtai_txt'] = '未知';
                break;
        }

        return_msg(200, 'success', $info);

    }

    public function getFreePolicyInfo()
    {
        $id     = input('id');
//        $userId = input('user_id');
        if (!$id) {
            return_error('缺少政策id');
        }

//        if (!$userId) {
//            return_error('请先登录');
//        }
        /**
         * @var $info DataMsjx
         */
        $info = DataMsjx::query()->where('id', $id)->find();

        if (empty($info)) {
            return_error('未找到对应的政策');
        }
        // $tagArray  = explode(',', $info->qybq ?? '');
        // $tagMap    = DataQiyeBiaoqian::query()->whereIn('id', $tagArray)->select()->toArray();
        // $tagMap    = array_column($tagMap, 'name', 'id');
        // $tagResult = [];
        // foreach ($tagArray as $tag) {
        //     $tagResult[] = $tagMap[$tag] ?? '';
        // }
        // $info->setAttr('tag_txt', implode(',', $tagResult));
        //提交状态
        // $info->setAttr('sub_status_txt', $info->getSubmitStatusTxt($info->tj_status));
        //兑付日期
        $info->setAttr('redemption_date', $info->sbjzrq ? $info->getSbjzrqDate($info->sbjzrq) : '');
        //出台发布日期
        $info->setAttr('release_date', $info->ctrq ? $info->getCtrqDate($info->ctrq) : '');
        $enterpriseBandPolicy = null;
//        $userBandEnterprise   = DataQiyeRzinfo::query()->where('user_id', $userId)->where('status', 1)
//            ->where('deleted', 0)->find();
//        if (!$userBandEnterprise) {
//            return_error('您还未绑定企业');
//        }
//        $enterpriseId = $userBandEnterprise->getAttr('qrxxk_id');
//        $enterprise   = DataQiyeXinxiku::query()->where('id', $enterpriseId)->find();
//        if (!$enterprise) {
//            return_error('企业信息不存在');
//        }
        //查看企业命中的政策条款
//        $freePolicy = DataEnterpriseFreePolicy::query()->where('enterprise_id', $enterpriseId)->where('policy_id', $id);
//        if ($freePolicy = $freePolicy->find()) {
//            $freePolicy->setAttr('status_txt', $freePolicy->getStatusTxt($freePolicy->status));
//        }
//        $hitList = DataEnterpriseFreePolicy::query()->where('enterprise_id', $enterpriseId)->where('policy_id', $id)->with('item')->select();
//
//        foreach ($hitList as $item) {
//            $enterpriseBandPolicy[] = ['policy_name' => $item->item->content ?? ''];
//        }

        $enterpriseBandPolicy = [];
        $info->setAttr('hit_list', $enterpriseBandPolicy);
        //企业命中的政策
//        $info->setAttr('free_policy', $freePolicy);
        $info->setAttr('ctrq', date('Y-m-d', $info->ctrq));
        return_msg(200, 'success', $info->toArray());
    }

    public function getFreePolicyInfobak()
    {
        $id     = input('id');
        $userId = input('user_id');
        if (!$id) {
            return_error('缺少政策id');
        }

        if (!$userId) {
            return_error('请先登录');
        }
        /**
         * @var $info DataMsjx
         */
        $info = DataMsjx::query()->where('id', $id)->find();

        if (empty($info)) {
            return_error('未找到对应的政策');
        }
        // $tagArray  = explode(',', $info->qybq ?? '');
        // $tagMap    = DataQiyeBiaoqian::query()->whereIn('id', $tagArray)->select()->toArray();
        // $tagMap    = array_column($tagMap, 'name', 'id');
        // $tagResult = [];
        // foreach ($tagArray as $tag) {
        //     $tagResult[] = $tagMap[$tag] ?? '';
        // }
        // $info->setAttr('tag_txt', implode(',', $tagResult));
        //提交状态
        // $info->setAttr('sub_status_txt', $info->getSubmitStatusTxt($info->tj_status));
        //兑付日期
        $info->setAttr('redemption_date', $info->sbjzrq ? $info->getSbjzrqDate($info->sbjzrq) : '');
        //出台发布日期
        $info->setAttr('release_date', $info->ctrq ? $info->getCtrqDate($info->ctrq) : '');
        $enterpriseBandPolicy = null;
        $userBandEnterprise   = DataQiyeRzinfo::query()->where('user_id', $userId)->where('status', 1)
            ->where('deleted', 0)->find();
        if (!$userBandEnterprise) {
            return_error('您还未绑定企业');
        }
        /**
         * @var $freePolicy DataEnterpriseFreePolicy
         */
        $enterpriseId = $userBandEnterprise->getAttr('qrxxk_id');
        $enterprise   = DataQiyeXinxiku::query()->where('id', $enterpriseId)->find();
        if (!$enterprise) {
            return_error('企业信息不存在');
        }
        //查看企业命中的政策条款
        $freePolicy = DataEnterpriseFreePolicy::query()->where('enterprise_id', $enterpriseId)->where('policy_id', $id);
        if ($freePolicy = $freePolicy->find()) {
            $freePolicy->setAttr('status_txt', $freePolicy->getStatusTxt($freePolicy->status));
        }
        $hitList = DataEnterpriseFreePolicy::query()->where('enterprise_id', $enterpriseId)->where('policy_id', $id)->with('item')->select();

        foreach ($hitList as $item) {
            $enterpriseBandPolicy[] = ['policy_name' => $item->item->content ?? ''];
        }
        $info->setAttr('hit_list', $enterpriseBandPolicy);
        //企业命中的政策
        $info->setAttr('free_policy', $freePolicy);
        $info->setAttr('ctrq', date('Y-m-d', $info->ctrq));
        return_msg(200, 'success', $info->toArray());
    }


    //获取免申即享最新进展
    public function getMsjxNewjinzhan()
    {

        $id = input('id');
        if (empty($id)) {
            return '';
        }

        $list = Db::name("data_msjx_jinzhan")->where('zc_id', $id)->select()->toArray();

        return_msg(200, 'success', $list);
    }


    //免申即享提交申请
    public function tijiaoSq()
    {

        $id      = input('id');
        $user_id = input('user_id');

        if (empty($id)) {
            return_error('缺少id');
        }

        if (empty($user_id)) {
            return_error('缺少user_id');
        }

        $info = Db::name("data_msjx")->where('id', $id)->find();

        if (empty($info)) {
            return_error('未找到文章记录');
        }

        if ($info['tj_status'] != 1) {
            return_error('当前状态不能申请');
        }


        $qiye = Db::name("data_qiye_rzinfo")->where('user_id', $user_id)->where('deleted', 0)->find();
        if (empty($qiye)) {
            return_error('未查询到企业认证信息');
        }

        $is_count = Db::name("data_msjx_user")->where('qrxxk_id', $qiye['qrxxk_id'])->where('msjx_id', $id)->count();

        if (!empty($is_count)) {
            return_error('请勿重复申请');
        }


        $data_msjx_user = [
            'user_id'     => $user_id,
            'msjx_id'     => $id,
            'code'        => $info['code'],
            'title'       => $info['title'],
            'admin_id'    => $info['admin_id'],
            'qymc'        => $qiye['qymc'],
            'tyxydm'      => $qiye['tyxydm'],
            'sbr_xm'      => $qiye['sbr_xm'],
            'sbr_phone'   => $qiye['sbr_phone'],
            'create_time' => time(),
            'qrxxk_id'    => $qiye['qrxxk_id'],
        ];

        Db::name("data_msjx_user")->insert($data_msjx_user);

        return_msg(200, '提交成功');
    }


    //我的申请
    public function myTijiaoList()
    {
        $user_id = input('user_id');

        if (empty($user_id)) {
            return_error('缺少参数user_id');
        }

        $qiye = Db::name("data_qiye_rzinfo")->where('user_id', $user_id)->where('deleted', 0)->find();
        if (empty($qiye)) {
            return_error('未查询到企业认证信息');
        }

        $page  = input('page', 1);
        $limit = input('limit', 10);
        $key   = input('key');

        $where['deleted']  = 0;
        $where['qrxxk_id'] = $qiye['qrxxk_id'];
        if (!empty($key)) {
            $where[] = ['title', 'like', '%' . $key . '%'];
        }

        $list = Db::name('data_msjx_user')->where($where)->order('create_at desc')->paginate($limit, false, ['page' => $page]);

        // 引用方式遍历集合并修改数据
        $list->each(function (&$item)
        {
            if (!empty($item['admin_id'])) {
                $item['admin_name'] = Db::name("system_user")->where('id', $item['admin_id'])->value('nickname');
            } else {
                $item['admin_name'] = '';
            }

            $msjx = Db::name("data_msjx")->where('id', $item['msjx_id'])->find();

            if (!empty($msjx['sbjzrq'])) {
                if ($msjx['sbjzrq'] > time()) {

                    // 计算剩余秒数
                    $remainingSeconds = $msjx['sbjzrq'] - time();

                    if ($remainingSeconds >= 86400) { // 大于等于 1 天
                        // 计算剩余天数
                        $remainingDays = floor($remainingSeconds / 86400);
                        $item['syts']  = "{$remainingDays}天";
                    } else {
                        // 小于 1 天，计算剩余小时数
                        $remainingHours = floor($remainingSeconds / 3600);
                        $item['syts']   = "{$remainingHours}小时";
                    }
                } else {
                    $item['syts'] = '已结束';
                }

            } else {
                $item['syts'] = '';
            }

            return $item;
        });

        // 获取分页数据
        $data = [
            'list'      => $list->items(),
            'total'     => $list->total(),
            'last_page' => $list->lastPage(),
        ];

        // 输出分页数据
        return_msg(200, '查询成功', $data);


    }


    //免申即享评价
    public function pingjia()
    {

        $id      = input('id');
        $user_id = input('user_id');
        $pf      = input('pf');
        $pjnr    = input('pjnr');


        if (empty($id)) {
            return_error('缺少参数');
        }

        $info = Db::name("data_msjx_user")->where('msjx_id', $id)->find();
        if (empty($info)) {
            return_error('未查询到相应记录');
        }

        //        if($info['user_id'] != $user_id){
        //            return_error('只可对自己的发布评价');
        //        }

        Db::name("data_msjx_user")->where('id', $info['id'])->update(['pf' => $pf, 'pjnr' => $pjnr]);

        return_msg(200, '操作成功');
    }
}
